﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Reflection;
using System.Web.Routing;
using MvcEngine.Core;

using MvcEngine.Core.Repositories;
using MvcEngine.Mvc.Models.ViewModels;
using MvcEngine.Mvc.Filters;
using MvcEngine.Core.Services;
using MvcEngine.Core.Helpers;
using MvcEngine.Core.Content;
using MvcEngine.Mvc.Controllers;
using MvcEngine.Mvc.Models;
using MvcEngine.Mvc.Extensions;

namespace MvcEngine.Mvc.StarterSite.Controllers
{
    public class HomeController : BaseController
    {
        //public MvcEngineModel Admin(Guid pageId, string actionName, string controlKey)
        //{
        //    Control control = ContentManager.Current.GetControlByKey(controlKey);
        //    BaseController ctrl = (BaseController)IoC.Resolve(Type.GetType(control.ControllerType));
        //    Dictionary<string, object> values = GetRouteValues(control.ModuleId, -1);

        //    AddEditContainer();
        //    AddControl("Edit_Pane", null, null, control, actionName, false, ctrl, values);
        //    return Index(pageId, null, actionName, true);
        //}

        //public MvcEngineModel Edit(Guid pageId, string actionName, int ctrId)
        //{
        //    PageContent pageContent = ContentManager.Current.GetPageContent(ctrId);
        //    Control control = ContentManager.Current.GetControl(pageContent.ControlId);

        //    BaseController ctrl = (BaseController)IoC.Resolve(Type.GetType(control.ControllerType));
        //    Dictionary<string, object> values = GetRouteValues(control.ModuleId, ctrId);

        //    AddEditContainer();
        //    AddControl("Edit_Pane", pageContent.Id, null, control, actionName, false, ctrl, values);
        //    return Index(pageId, ctrId, actionName, true);
        //}

        public MvcEngineModel Menu()
        {
            var pages = ContentManager.Current.GetPages(true);

            var visiblePages = new List<Page>();
            foreach (var item in pages)
            {
                if (PermissionHelper.Current.HasRights(item.Id, PermissionTypes.View))
                    visiblePages.Add(item);
            }
            return new SiteMenuViewModel() { Pages = visiblePages, SelectedPage = SiteContext.Current.CurrentPage, ViewName = "Menu" };
        }

        public MvcEngineModel Index(Guid pageId/*, int? ctrId, string actionName, bool? indexOnly*/)
        {
            var model = new PageHeaderViewModel() { ViewName = "Markup" };

            var controlKey = (string)this.RouteData.Values["controlKey"];
            if (!string.IsNullOrEmpty(controlKey))
            {
                var control = ContentManager.Current.GetControlByKey(controlKey);
                if (control != null)
                {
                    Type controlServiceType = Type.GetType(control.ControlServiceType);
                    IControlService controlService = (IControlService)IoC.Resolve(controlServiceType);
                    var controllerDescriptor = new ReflectedControllerDescriptor(controlService.GetControllerType());

                    var actionDescriptor = controllerDescriptor.FindAction(this.ControllerContext, (string)this.RouteData.Values["actionName"]);

                    if (actionDescriptor != null)
                    {
                        var attr = ((PageHeaderAttribute)(actionDescriptor.GetCustomAttributes(typeof(PageHeaderAttribute), false)).SingleOrDefault());
                        if (attr != null)
                        {
                            var pageHeader = attr.Get(ControllerContext.RequestContext);
                            if (pageHeader != null)
                            {
                                model.Title = pageHeader.Title;
                                model.Keywords = pageHeader.Keywords;
                                model.Description = pageHeader.Description;
                            }
                        }
                    }
                }
            }

            var pageContents = ContentManager.Current.GetPageContents(pageId);
            foreach (var item in pageContents)
            {
                var control = ContentManager.Current.GetControl(item.ControlId);
                var module = ContentManager.Current.GetModule(control.ModuleId);
                IControlService service = (IControlService)IoC.Resolve(Type.GetType(control.ControlServiceType));

                foreach (var styleSheet in service.GetStyleSheets())
                {
                    model.StyleSheetPaths.Add(Url.GetModuleCssPath(styleSheet, module.Name));
                }
            }

            return model;


            //var pageContentRepository = IoC.Resolve<IPageContentRepository>();

            //var moduleContainers = GetModuleContainer();
            //PageContent pageContent = null;

            //if (ctrId.HasValue && !indexOnly.HasValue)
            //{
            //    pageContent = ContentManager.Current.GetPageContent(ctrId.Value);
            //    AddRouteControl(pageContent, actionName);
            //}

            //foreach (var item in contents)
            //{
            //    if (item.MaxModuleCount.HasValue && moduleContainers[item.ContainerMarkupId].Count >= item.MaxModuleCount.Value)
            //    {
            //        continue;
            //    }

            //    Control control = ContentManager.Current.GetControl(item.ControlId);
            //    BaseController ctrl = (BaseController)IoC.Resolve(Type.GetType(control.ControllerType));
            //    Dictionary<string, object> values = GetRouteValues(control.ModuleId, item.Id);
            //    if (pageContent != null && item.Id == pageContent.Id && !indexOnly.HasValue)
            //    {
            //        AddControl(item, control, actionName, false, ctrl, values);
            //    }
            //    else
            //    {
            //        AddControl(item, control, control.DefaultAction, true, ctrl, values);
            //    }
            //}

            //MvcEngineModel model = new MvcEngineModel();

            //Dictionary<string, string> items = this.HttpContext.Items["AdditionalData"] as Dictionary<string, string>;
            //if (items != null)
            //{
            //    model.AddModelItem<Dictionary<string, string>>(items);
            //}

            //model.AddModelItem(moduleContainers);
            //return model;
        }

        //#region Private methods

        //private void AddEditContainer()
        //{
        //    var moduleContainers = GetModuleContainer();
        //    moduleContainers["Edit_Pane"] = new List<ControlData>();
        //}

        //private Dictionary<string, List<ControlData>> GetModuleContainer()
        //{
        //    return this.TempData["moduleCotainers"] as Dictionary<string, List<ControlData>>;
        //}

        //private void AddRouteControl(PageContent pageContent, string actionName)
        //{
        //    Control control = ContentManager.Current.GetControl(pageContent.ControlId);
        //    Type controllerType = Type.GetType(control.ControllerType);
        //    BaseController ctrl = (BaseController)IoC.Resolve(controllerType);
        //    Dictionary<string, object> values = GetRouteValues(control.ModuleId, pageContent.Id);
        //    Container container = ContentManager.Current.GetContainer(pageContent.ContainerId);

        //    AddControl(container.MarkupId, pageContent.Id, null, control, actionName, false, ctrl, values);
        //}

        //private Dictionary<string, object> GetRouteValues(Guid moduleId, int ctrId)
        //{
        //    Dictionary<string, object> values = new Dictionary<string, object>();
        //    values["ctrId"] = ctrId;
        //    values["moduleName"] = ContentManager.Current.GetModule(moduleId).Name;
        //    return values;
        //}

        //private void AddControl(PageContentDetails pageContent, Control control, string action, bool isDefaultAction, BaseController ctrl, Dictionary<string, object> values)
        //{
        //    AddControl(pageContent.ContainerMarkupId, pageContent.Id, pageContent.ContentName, control, action, isDefaultAction, ctrl, values);
        //}

        //private void AddControl(string markupId, int? pageContentId, string contentName, Control control, string action, bool isDefaultAction, BaseController ctrl, Dictionary<string, object> values)
        //{
        //    var moduleContainers = GetModuleContainer();

        //    if (moduleContainers[markupId].Exists(c => c.ActionName == action && c.PageContentId == pageContentId && c.ControllerType == ctrl.GetType()))
        //        return;

        //    if (!PermissionHelper.Current.HasRights(control.Id, ModulePermissions.View))
        //        return;

        //    values["controlId"] = control.Id;

        //    Action act = ctrl.GetResult(this, action, isDefaultAction, values);
        //    if (act != null)
        //    {
        //        moduleContainers[markupId].Add(new ControlData()
        //        {
        //            Action = act,
        //            ActionName = action,
        //            Control = control,
        //            PageContentId = pageContentId,
        //            ControllerType = ctrl.GetType(),
        //            ContentName = contentName
        //        });
        //    }
        //}

        //#endregion
    }
}
